#!/usr/bin/make -f
DH_VERBOSE = 1

.PHONY: override_dh_strip

%:
	dh $@ --with bash-completion,systemd

# dh_auto_clean tries to invoke distutils causing failures.
override_dh_auto_clean:
	rm -rf build
	rm -rf debian/salt-common
	rm -rf debian/salt-minion
	rm -rf debian/salt-master
	rm -rf debian/salt-syndic
	rm -rf debian/salt-ssh

ifeq ("${SALT_ONEDIR_ARCHIVE}", "")
override_dh_auto_build:
	export PIP_CONSTRAINT=requirements/constraints.txt
	export FETCH_RELENV_VERSION=$${SALT_RELENV_VERSION}
	mkdir -p build/onedir
	python3 -m venv --clear --copies build/onedir/venv
	build/onedir/venv/bin/python3 -m pip install relenv==$${SALT_RELENV_VERSION}
	export FETCH_RELENV_VERSION=$${SALT_RELENV_VERSION}
	export PY=$$(build/onedir/venv/bin/python3 -c 'import sys; sys.stdout.write("{}.{}".format(*sys.version_info)); sys.stdout.flush()') \
		&& build/onedir/venv/bin/python3 -m pip install -r requirements/static/ci/py$${PY}/tools.txt
	build/onedir/venv/bin/relenv fetch --python=$${SALT_PYTHON_VERSION}
	build/onedir/venv/bin/pip3 install relenv[toolchain]
	build/onedir/venv/bin/relenv toolchain fetch
	build/onedir/venv/bin/tools pkg build onedir-dependencies --arch $${SALT_PACKAGE_ARCH} --relenv-version=$${SALT_RELENV_VERSION} --python-version $${SALT_PYTHON_VERSION} --package-name build/onedir/salt --platform linux

	# Fix any hardcoded paths to the relenv python binary on any of the scripts installed in the <onedir>/bin directory
	find build/onedir/salt/bin/ -type f -exec sed -i 's:#!/\(.*\)salt/bin/python3:#!/bin/sh\n"exec" "$$(dirname $$(readlink -f $$0))/python3" "$$0" "$$@":g' {} \;

	build/onedir/venv/bin/tools pkg build salt-onedir . --package-name build/onedir/salt --platform linux
	build/onedir/venv/bin/tools pkg pre-archive-cleanup --pkg build/onedir/salt

else
override_dh_auto_build:
	# The relenv onedir is being provided, all setup up until Salt is installed
	# is expected to be done
	mkdir -p build/onedir
	cd build/onedir; tar xvf ${SALT_ONEDIR_ARCHIVE}

	# Fix any hardcoded paths to the relenv python binary on any of the scripts installed in the <onedir>/bin directory
	find build/onedir/salt/bin/ -type f -exec sed -i 's:#!/\(.*\)salt/bin/python3:#!/bin/sh\n"exec" "$$(dirname $$(readlink -f $$0))/python3" "$$0" "$$@":g' {} \;

endif

# dh_auto_install tries to invoke distutils causing failures.
override_dh_auto_install:


override_dh_install:
	mkdir -p debian/salt-common/opt/saltstack
	cp -R build/onedir/salt debian/salt-common/opt/saltstack/

        # Generate master config
	mkdir -p debian/salt-master/etc/salt
	sed 's/#user: root/user: salt/g' conf/master > debian/salt-master/etc/salt/master

	dh_install

override_dh_strip:
	dh_strip --dbg-package=salt-dbg
